package com.lw.extraceim.ui.activity.tp;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ListView;

import androidx.annotation.Nullable;

import com.google.gson.reflect.TypeToken;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
import com.lw.extraceim.R;
import com.lw.extraceim.loader.ExpressSheetLoader;
import com.lw.extraceim.loader.PackageLoader;
import com.lw.extraceim.model.ExpressSheet;
import com.lw.extraceim.model.TransPackage;
import com.lw.extraceim.net.HttpResponseParam;
import com.lw.extraceim.net.ResponseCode;
import com.lw.extraceim.net.callback.HttpResponseParamCallback;
import com.lw.extraceim.ui.activity.base.BaseActivity;
import com.lw.extraceim.ui.adapter.ExpressSheetAdapter;
import com.lw.extraceim.util.JsonUtils;
import com.lw.extraceim.view.ExtraceToolbar;
import com.lw.extraceim.zxing.ExtraceCaptureActivity;

import org.json.JSONException;

import java.util.List;
import java.util.Objects;

import okhttp3.Call;

/**
 * @Author : liwei
 * @Email : 1759840027@qq.com
 * @Description : 拆包
 * @Date : 2019/5/27 18:04
 */
public class UnpackageInfoActivity extends BaseActivity {
    private static final String TAG = "UnpackageInfoActivity";
    private ExtraceToolbar mToolbar;
    private EditText mEdPackageNo;
    private EditText mEdPackageStatus;
    private EditText mEdPackageFrom;
    private EditText mEdPackageTo;
    private TransPackage transPackage;
    private ListView mEsListView;

    private List<ExpressSheet> expressSheetList;
    private ExpressSheetAdapter expressSheetAdapter;

    private PackageLoader packageLoader;

//    private


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    public void initView() {
        setContentView(R.layout.activity_unpackage_info);
        mToolbar = findViewById(R.id.toolbar);
        initToolBar();
        mEdPackageNo = findViewById(R.id.ed_package_no);
        mEdPackageNo.setEnabled(false);
        mEdPackageStatus = findViewById(R.id.ed_package_status);
        mEdPackageStatus.setEnabled(false);
        mEdPackageFrom = findViewById(R.id.ed_package_from);
        mEdPackageFrom.setEnabled(false);
        mEdPackageTo = findViewById(R.id.ed_package_to);
        mEdPackageTo.setEnabled(false);
        mEsListView = findViewById(R.id.es_list_view);
    }

    /**
     * 初始化toolBar
     */
    protected void initToolBar() {
        setSupportActionBar(mToolbar);
        getSupportActionBar().setDisplayShowTitleEnabled(false);
        mToolbar.setBackButtonOnClickListerner(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                UnpackageInfoActivity.this.finish();
            }
        });
        mToolbar.setRightButtonText("下一步");
        mToolbar.setButtonOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showDialog("提示", "扫描快件", "确认", "取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        startQRScan(UnpackageInfoActivity.this, ExtraceCaptureActivity.class, "扫描快件", ExtraceCaptureActivity.SCAN_UNPACK_ES);
                    }
                }, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
            }
        });
    }

    @Override
    public void initData() {
        packageLoader = new PackageLoader(this);
        transPackage = (TransPackage) getIntent().getSerializableExtra("transPackage");
        if (transPackage != null) {
            loadPackage(transPackage.getId());
            loadEsList(transPackage.getId());
        } else {
            showDialog("提示", "包裹信息错误", "确认", null, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    finish();
                }
            }, null);
        }
    }

    @Override
    public void refreshUI() {
        refreshPackage();
        refreshEsList();
    }

    //更新页面上的包裹信息
    protected void refreshPackage() {
        if (transPackage != null) {
            mEdPackageNo.setText(transPackage.getId());
            mEdPackageStatus.setText(transPackage.getStatusString());
            mEdPackageFrom.setText(transPackage.getSourceNode());
            mEdPackageTo.setText(transPackage.getTargetNode());
        } else {
            showDialog("提示", "包裹信息不存在", "确认", null, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    UnpackageInfoActivity.this.finish();
                }
            }, null);
        }
    }

    /**
     * 更新页面上的快件列表信息
     */
    protected void refreshEsList() {
        mEsListView.setAdapter(new ExpressSheetAdapter(expressSheetList, this));
    }


    @Override
    public void initEvent() {
    }

    //加载包裹信息
    public void loadPackage(final String packageId) {
        PackageLoader loader = new PackageLoader(this);
        if (packageId != null) {
            loader.get(packageId, new HttpResponseParamCallback() {
                @Override
                public void onError(Call call, Exception e, int id) {
                    alert("网络错误" + e.getMessage());
                }

                @Override
                public void onResponse(HttpResponseParam response, int id) {
                    Log.d(TAG, "onResponse: " + response.reseponseJson);
                    if (response.code.getCode() == ResponseCode.SUCESS) {
                        try {
                            transPackage = JsonUtils.fromJson(response.reseponseJson.getJSONObject("package").toString(), new TypeToken<TransPackage>() {
                            });
                            refreshPackage();
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    } else if (response.code.getCode() == ResponseCode.FIAL) {
                        showDialog("提示", "包裹信息不存在", "确认", null, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                UnpackageInfoActivity.this.finish();
                            }
                        }, null);

                    }
                }
            });
        }

    }

    /**
     * 加载包裹中的快件信息
     *
     * @param packageId
     */
    public void loadEsList(final String packageId) {
        ExpressSheetLoader loader = new ExpressSheetLoader(this);
        if (packageId != null) {
            loader.getEsList(packageId, new HttpResponseParamCallback() {
                @Override
                public void onError(Call call, Exception e, int id) {
                    alert("网络错误" + e.getMessage());
                }

                @Override
                public void onResponse(HttpResponseParam response, int id) {
                    Log.d(TAG, "onResponse: " + response.reseponseJson);
                    if (response.code.getCode() == ResponseCode.SUCESS) {
                        try {
                            expressSheetList = JsonUtils.fromJson(response.reseponseJson.getJSONArray("esList").toString(), new TypeToken<List<ExpressSheet>>() {
                            });
                            refreshEsList();
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    } else if (response.code.getCode() == ResponseCode.FIAL) {
                        showDialog("提示", "包裹信息不存在", "确认", null, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                UnpackageInfoActivity.this.finish();
                            }
                        }, null);

                    }
                }
            });
        }
    }

    //从包裹中移出快件
    public void moveEsOutPackage(final String esId) {
        packageLoader.moveEsOutPackage(transPackage.getId(), esId, new HttpResponseParamCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                alert("网络错误" + e.getMessage());
            }

            @Override
            public void onResponse(HttpResponseParam response, int id) {
                if (response.code.getCode() == ResponseCode.SUCESS) {
                    //从包裹中移出快件成功
                    for (int i = 0; i < expressSheetList.size(); i++) {
                        if (Objects.equals(expressSheetList.get(i).getId(), esId)) {
                            expressSheetList.remove(i);
                            break;
                        }
                    }
                    if (expressSheetList.isEmpty()) {
                        showDialog("提示", "快件已全部移出", "完成拆包", null, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                unPackage();
                            }
                        }, null);

                    } else {
                        showDialog("提示", "是否继续?", "继续", "结束拆包", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                startQRScan(UnpackageInfoActivity.this, ExtraceCaptureActivity.class, "扫描快件", ExtraceCaptureActivity.SCAN_UNPACK_ES);
                            }
                        }, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                                alert("缺失" + expressSheetList.size() + "个快件");
                            }
                        });
                    }

                } else {
                    alert(response.code.getMessage());
                }
            }
        });
    }

    //最后拆包
    public void unPackage() {
        packageLoader.unpack(transPackage.getId(), application.getUserInfo().getuId(), new HttpResponseParamCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                alert("网络错误" + e.getMessage());
            }

            @Override
            public void onResponse(HttpResponseParam response, int id) {
                if (response.code.getCode() == ResponseCode.SUCESS) {
                    showDialog("提示", "拆包完成", "确认", null, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            finish();
                        }
                    }, null);
                }
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        loadEsList(transPackage.getId());
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        switch (requestCode) {
            case ExtraceCaptureActivity.SCAN_UNPACK_ES: {
                IntentResult scanResult = IntentIntegrator.parseActivityResult(IntentIntegrator.REQUEST_CODE, resultCode, data);
                if (scanResult != null) {
                    String expressSheetId = scanResult.getContents();
                    moveEsOutPackage(expressSheetId); //移出快件
                }
            }
        }
    }

    @Override
    public void onBackPressed() {
        this.finish();
    }

    public static void actionStart(Context context, TransPackage transPackage) {
        Intent intent = new Intent(context, UnpackageInfoActivity.class);
        Bundle bundle = new Bundle();
        bundle.putSerializable("transPackage", transPackage);
        intent.putExtras(bundle);
        context.startActivity(intent);
    }
}
